<?php
/**
 * handle xupload action method
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
Yii::import('common.extensions.xupload.actions.XUploadAction');
class ResourceUploadAction extends XUploadAction{
    protected function beforeReturn() {
        if(parent::beforeReturn()){
            $subFolder = $this->getSubFolder() != '' ? $this->getSubFolder() . '/' : '';

            //create new gallery item and save to db
            $model = new Resource;
            $model->resource_name = $this->formModel->{$this->fileNameAttribute};
            $model->resource_path = $subFolder . $this->formModel->{$this->displayNameAttribute};
            $model->resource_type = 'image';
            $model->where = Resource::WHERE_EXTERNAL;
            $model->user_id = user()->id;

            if($model->save()){
                return $model->resource_id;
            }else{
                return false;
            }
        }

        return false;
    }

    /**
     * overide xupload form
     * @throws CHttpException
     */
    protected function handleUploading() {
        $this->init();
        $model = $this->formModel;
        $model->{$this->fileAttribute} = CUploadedFile::getInstance($model, $this->fileAttribute);
        if ($model->{$this->fileAttribute} !== null) {
            $model->{$this->mimeTypeAttribute} = $model->{$this->fileAttribute}->getType();
            $model->{$this->sizeAttribute} = $model->{$this->fileAttribute}->getSize();
            $model->{$this->displayNameAttribute} = $model->{$this->fileAttribute}->getName();
            $model->{$this->fileNameAttribute} = $model->{$this->displayNameAttribute};

            if ($model->validate()) {

                $path = $this->getPath();

                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                    chmod($path, 0777);
                }

                $model->{$this->fileAttribute}->saveAs($path . $model->{$this->fileNameAttribute});

                chmod($path . $model->{$this->fileNameAttribute}, 0777);

                $returnValue = $this->beforeReturn();
                if ($returnValue !== FALSE) {
                    //save gallery item
                    echo json_encode(array(array(
                        "name" => $model->{$this->displayNameAttribute},
                        "type" => $model->{$this->mimeTypeAttribute},
                        "size" => $model->{$this->sizeAttribute},
                        "url" => $this->getFileUrl($model->{$this->fileNameAttribute}),
                        "thumbnail_url" => $model->getThumbnailUrl($this->getPublicPath()),
                        "delete_url" => $this->getController()->createUrl($this->getId(), array(
                            "_method" => "delete",
                            "file" => $model->{$this->fileNameAttribute},
                            'resource_id' => $returnValue
                        )),
                        "delete_type" => "POST"
                    )));
                } else {
                    echo json_encode(array(array("error" => $returnValue,)));
                    Yii::log("XUploadAction: " . $returnValue, CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction");
                }
            } else {
                echo json_encode(array(array("error" => $model->getErrors($this->fileAttribute),)));
                Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction");
            }
        } else {
            throw new CHttpException(500, "Could not upload file");
        }
    }

    /**
     * Removes temporary file from its directory and from the session
     * Overide parent
     * @return bool Whether deleting was meant by request
     */
    protected function handleDeleting()
    {
        if (isset($_GET["_method"]) && $_GET["_method"] == "delete" && $_GET['resource_id']) {
            //delete item in db
            $model = Resource::model()->findByPk($_GET['resource_id']);
            if($model){
                echo json_encode($model->delete());
            }else{
                echo json_encode(FALSE);
            }

            return true;
        }
        return false;
    }
}